cmake_minimum_required(VERSION 3.10)

# 设置 C/C++ 标准
set(C_STANDARD 17)
set(CMAKE_CXX_STANDARD 17)
set(VM_TYPE)
# for test only
add_definitions(-DVM_TYPE=${VM_TYPE})

set(COMPILE_FLAGS -O3 -flto=thin)
add_compile_options(${COMPILE_FLAGS})

# 项目名称
project(JSIExecutor)

# 根据不同的平台设置
if(WIN32)
  message(STATUS "Now is Windows")
elseif(APPLE)
  message(STATUS "Now is Apple")
elseif(UNIX)
  message(STATUS "Now is UNIX")
  add_definitions(-D_GNU_SOURCE)  # 特定于 Unix 系统的定义
endif()

# 选项：启用 AddressSanitizer
option(ENABLE_ASAN "Enable AddressSanitizer" OFF)

if(ENABLE_ASAN)
  if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
    set(SANITIZER_FLAGS "-fsanitize=address")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SANITIZER_FLAGS} -g")
    set(CMAKE_LINKER_FLAGS "${CMAKE_LINKER_FLAGS} ${SANITIZER_FLAGS}")
  endif()
endif()

add_subdirectory(src)
add_subdirectory(tests/common)

# 公共设置：包含公共的 include 目录
function(set_common_includes)
  include_directories(
    ${PROJECT_SOURCE_DIR}/src
    ${PROJECT_SOURCE_DIR}/third_party
    ${PROJECT_SOURCE_DIR}/tests
    ${PROJECT_SOURCE_DIR}/bin
  )
endfunction()

# qjs 相关的设置
function(qjs)
  # 添加子目录
  add_subdirectory(third_party/QuickJS)

  # tests file
  add_subdirectory(tests/quickjs)

  target_link_libraries(${PROJECT_NAME} quickjs)

endfunction()

# jsvm 相关的设置
function(jsvm)
  # 添加子目录

  # tests file
  add_subdirectory(tests/jsvm)

  target_link_libraries(${PROJECT_NAME} jsvm_executor_common)
endfunction()

# 设置公共的 include 目录
set_common_includes()

add_executable(${PROJECT_NAME}
  bin/main.cpp
  bin/Options.cpp
)
target_link_libraries(${PROJECT_NAME} engine)

function(jsc)
  set_common_includes()

  # tests file
  add_subdirectory(tests/jsc)
  target_link_libraries(${PROJECT_NAME} jsc_executor_common)

endfunction()

# 根据 VM_TYPE 调用对应的函数
if(VM_TYPE STREQUAL "QJS")
  add_definitions(-DQJS)
  qjs()
elseif(VM_TYPE STREQUAL "JSVM")
  jsvm()
elseif(VM_TYPE STREQUAL "JSC")
  jsc()
else()
  message(FATAL_ERROR "Invalid VM_TYPE: ${VM_TYPE}. Valid values are 'QJS' or 'JSVM'.")
endif()
